<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<script type="text/javascript">
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function addrows(){
        if( $('#inputForm').parsley().validate()){
        var list=$("table tr").find("td:eq(0)");
        var data=[];
        var dataJson={};
        for(var i=0;i<list.length;i++){
            dataJson=jQuery.parseJSON(list[i].innerText);
            data.push(dataJson);
        }
        var flag=0;
        if(data.length!=0){
            for(var j=0;j<data.length;j++){
                if(data[j].infoId==$("#infoId").val()&&$('#updateBy').val()==data[j].updateBy){
                    flag=1;
                    break;
                }
            }
        }
        if(flag==1){
            toastr.info('该药品已存在，不能重复添加');
        }
        else if(flag==0){
            var jsonuserinfo= $("#inputForm").serializeObject();
            jsonuserinfo.packageUnits=$('#packageUnits').val();
            jsonuserinfo.minUnits=$('#minUnits').val();
            jsonuserinfo.packageUnitsName=$("#packageUnits").find("option:selected").text();
            jsonuserinfo.minUnitsName=$("#minUnits").find("option:selected").text();
            var datastr = JSON.stringify(jsonuserinfo);
            var trHTML = "<tr>";
            trHTML += "<td hidden>"+datastr +"</td>";
            trHTML += "<td>"+$('#remarks').val() +"</td>";
            trHTML += "<td>"+$('#packageSpec').val() +"</td>";
            trHTML += "<td hidden>"+$('#packageUnits').val() +"</td>";
            trHTML += "<td>"+$("#packageUnits").find("option:selected").text() +"</td>";
            trHTML += "<td>"+$('#minSpec').val() +"</td>";
            trHTML += "<td hidden>"+$('#minUnits').val() +"</td>";
            trHTML += "<td>"+$("#minUnits").find("option:selected").text() +"</td>";
            trHTML += "<td>"+$('#updateBy').val() +"</td>";
            trHTML += "<td>"+$('#purchasePrice').val() +"</td>";
            trHTML += "<td>"+$('#batchNo').val() +"</td>";
            trHTML += "<td>"+$('#expireDate').val() +"</td>";
            trHTML += "<td>"+$('#quantity').val() +"</td>";
            trHTML += "<td>"+$('#quantity').val()*$('#purchasePrice').val() +"</td>";
            trHTML += "<td><a href='#' onclick='updateList(this)' class='btn btn-success btn-xs'>修改</a>"+"<a href='#' onclick='removeList(this)' class='applyBt btn btn-danger btn-xs'>删除</a></td>"
            trHTML += "</tr>";
            $("#inputForm input").val("");
//        fillForm($("#inputForm"),datastr);
            $("#contentTable").append(trHTML);
            totalPrice();
            return loadDiv('rigthCenterDiv','${ctx}/drug/drugStock/form');
        }
    }
    }

    //表单自动回填的方法
    var fillForm = function($form, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        for ( var key in jsonObj) { // 遍历json字符串
            var objtype = jsonObjType(jsonObj[key]); // 获取值类型
            if (objtype === "array") { // 如果是数组，一般都是数据库中多对多关系
                var obj1 = jsonObj[key];
                for ( var arraykey in obj1) {
                    // alert(arraykey + jsonObj[arraykey]);
                    var arrayobj = obj1[arraykey];
                    for ( var smallkey in arrayobj) {
                        setCkb(key, arrayobj[smallkey]);
                        break;
                    }
                }
            } else if (objtype === "object") { // 如果是对象，啥都不错，大多数情况下，会有 xxxId
                // 这样的字段作为外键表的id

            } else if (objtype === "string") { // 如果是字符串
                var str = jsonObj[key];
                var date = new Date(str);
                if (date.getDay()) { // 这种判断日期是本人懒，不想写代码了，大家慎用。
                    $("[name=" + key + "]", $form).val(str);
                    continue;
                }

                var tagobjs = $("[name=" + key + "]", $form);
                if ($(tagobjs[0]).attr("type") == "radio") {// 如果是radio控件
                    $.each(tagobjs, function(keyobj, value) {
                        if ($(value).attr("val") == jsonObj[key]) {
                            value.checked = true;
                        }
                    });
                    continue;
                }
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            } else { // 其他的直接赋值
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            }

        }
    }

    var setCkb = function(name, value) {
        // alert(name + " " + value);
        // $("[name=" + name + "][value=" + value + "]").attr("checked", "checked");
        // 不知为何找不到具体标签;
        $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
    }

    var fillckb = function(name, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        var str = jsonObj[name];
        if (typeof str === "string") {
            var array = str.split(",");
            $.each(array, function(key, value) {
                setCkb(name, value);
            });
        }
    }

    var jsonObjType = function(obj) {
        if (typeof obj === "object") {
            var teststr = JSON.stringify(obj);
            if (teststr[0] == '{' && teststr[teststr.length - 1] == '}')
                return "class";
            if (teststr[0] == '[' && teststr[teststr.length - 1] == ']')
                return "array";
        }
        return typeof obj;
    }
    //表单回填EN


</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li>
                <a href="#"  onclick="loadDiv('rigthCenterDiv','${ctx}/drug/drugStock/form')">入库处理</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12">
<form:form id="inputForm" data-parsley-validate=""  modelAttribute="drugStock" onsubmit="return formSaveLoad('mainCenterDiv','inputForm','${ctx}/drug/drugStock/save','${ctx}/drug/drugStock/index');" method="post" class="form-horizontal">
                    <form:hidden path="id"/>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品编码：</label>
                        <div class="col-sm-8">
                            <form:input path="drugCode" htmlEscape="false" class="form-control"  maxlength="32" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品名称：</label>
                        <div class="col-sm-8">
                            <form:input path="infoId" htmlEscape="false" class="form-control"  maxlength="64" type="hidden" />
                            <form:input path="remarks" htmlEscape="false" class="form-control"  maxlength="64" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="packageNum" htmlEscape="false" class="form-control"  maxlength="8" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装规格：</label>
                        <div class="col-sm-8">
                            <form:input path="packageSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group" id="packageUnits_add">
                        <label class="col-sm-4 control-label">包装单位：</label>
                        <div class="col-sm-8">
                            <form:select path="packageUnits" id="packageUnits" class="form-control"  disabled="true">
                                <form:option value="" label="" />
                                <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                            </form:select>
                        </div>
                    </div>
                    <div class="form-group" id="packageUnits_change" style="display: none">
                        <label class="col-sm-4 control-label">包装单位：</label>
                        <div class="col-sm-8">
                            <form:input path="packageUnitsName" class="form-control" id="packageUnitsName" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">最小规格：</label>
                        <div class="col-sm-8">
                            <form:input path="minSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true" />
                        </div>
                        </div>
                        <div class="form-group" id="minUnits_add">
                            <label class="col-sm-4 control-label">最小单位：</label>
                            <div class="col-sm-8">
                                <form:select path="minUnits" id="minUnits" class="form-control"  disabled="true">
                                    <form:option value="" label="" />
                                    <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group"  id="minUnits_change" style="display: none">
                            <label class="col-sm-4 control-label">最小单位：</label>
                            <div class="col-sm-8">
                                <form:input  path="minUnitsName" class="form-control"  id="minUnitsName" readonly="true" />
                            </div>
                        </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">厂家：</label>
                        <div class="col-sm-8"> <!--库存表没有厂家字段，为了在页面显示出来，借用updateBy字段-->
                            <form:input path="updateBy" htmlEscape="false" class="form-control"  maxlength="64" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">进货价：</label>
                        <div class="col-sm-8">
                            <form:input path="purchasePrice" htmlEscape="false" class="form-control" data-parsley-required="true" />
                        </div>
                    </div>
                    <%--<div class="form-group">--%>
                        <%--<label class="col-sm-4 control-label">折扣：</label>--%>
                        <%--<div class="col-sm-8">--%>
                            <%--<form:input path="discount" htmlEscape="false" class="form-control" value="1" />--%>
                        <%--</div>--%>
                    <%--</div>--%>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">批号：</label>
                        <div class="col-sm-8">
                            <form:input path="batchNo" htmlEscape="false" class="form-control"  maxlength="64" data-parsley-required="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">有效期：</label>
                        <div class="col-sm-8">
                            <input id="expireDate" name="expireDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" value='<fmt:formatDate value="${drugPrice.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>'/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">入库包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="quantity" htmlEscape="false" class="form-control"  maxlength="8" data-parsley-required="true" data-parsley-type="number"/>
                        </div>
                    </div>
</form:form>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="确 定" onclick="addrows()">&nbsp;
                        <input id="btnCancel" class="btn" type="button" value="关 闭" onclick="closeRight()"></div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
    /*药品自动补全*/
    autoCompleteDrugPrice("remarks");
    function autoCompleteDrugPrice(inputId){
        var url="${ctx}/drug/drugInfo/autoCompletePrice";
        autoComplete(inputId,url,
                function(data){
                    var rows = [];
                    for(var i=0; i<data.length; i++){
                        rows[rows.length] = {
                            data:data[i],
                            value:data[i].id,
                            result:data[i].drugDict.drugName
                        };
                    }
                    return rows;
                },function(data, i, max){
                    return data.drugDict.drugName+"|"+"|"+data.packageSpec+"|"+data.drugSupplierCata.supplierName+"|"+data.packUnitName+"|"+data.purchasePrice+"元";
                },function(event,data,formatted){
                    console.log(data);
                    $('#updateBy').attr('value',data.drugSupplierCata.supplierName);
                    $('#infoId').attr('value',data.id);
                    $('#drugCode').attr('value',data.drugDict.drugCode);
                    $('#packageSpec').attr('value',data.packageSpec);
                    $("#packageUnits option[value='"+data.packageUnit+"']").attr("selected", true);
                    $('#packageUnits').change();
                    $('#minSpec').attr('value',data.minSpec);
                    $('#purchasePrice').attr('value',data.purchasePrice);
                    $('#quantity').attr('value',0);
                    $("#minUnits option[value='"+data.minUnits+"']").attr("selected", true);
                    $('#minUnits').change();
                    $('#packageNum').attr('value',data.packageNum);
                })
    }
    function closeRight(){
        $("#stcokRightDiv").attr("style","display: none");
        $("#stcokLeftDiv").attr("class","main-content col-lg-12");
        $("#stcokLeftDiv").show('normal');
    }

</script>